<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.4.0/sockjs.min.js"></script>
    <script src="./lib/stomp.js"></script>
    <script>
        var ws = new WebSocket('ws://127.0.0.1:8000/ws-homehub/ws?userId=' + 10000);
        console.log('ws连接状态：' + ws.readyState);
        //监听是否连接成功
        ws.onopen = function () {
            console.log('ws连接状态：' + ws.readyState);
            //连接成功则发送一个数据
            ws.send('test1');
        };
        //接听服务器发回的信息并处理展示
        ws.onmessage = function (data) {
            console.log('接收到来自服务器的消息：');
            console.log(data);
            //完成通信后关闭WebSocket连接
            ws.close();
        };
        //监听连接关闭事件
        ws.onclose = function () {
            //监听整个过程中websocket的状态
            console.log('ws连接状态：' + ws.readyState);
        };
        //监听并处理error事件
        ws.onerror = function (error) {
            console.log(error);
        };

        function handleSend() {
            var msg = document.getElementById('sendMsg').value;
            // 发送到topic接口
            ws.send(msg);
            var $p = document.createElement('p');
            $p.innerText = msg + '----' + dateFtt(new Date())
        }
        function dateFtt(date, fmt) {
            if (!fmt) {
                fmt = 'yyyy-MM-dd hh:mm:ss'
            }
            var o = {
                "M+": date.getMonth() + 1,                 //月份
                "d+": date.getDate(),                    //日
                "h+": date.getHours(),                   //小时
                "m+": date.getMinutes(),                 //分
                "s+": date.getSeconds(),                 //秒
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                "S": date.getMilliseconds()             //毫秒
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }
    </script>
</head>
<body>
<div><input type="text" id="sendMsg">
    <button onclick="handleSend()">发送</button>
</div>
<div id="content"></div>
</body>
</html>
